﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Collections;

namespace FileHelpers
{
    /// <summary>
    /// Classe responsavel por converter uma string com varios registros em uma lista de registros
    /// </summary>
    public class ObjectListConverter<T> : ConverterBase
    {
        private int _recordSize;
        private RecordInfo _ri;

        public ObjectListConverter()
        {
            _ri = new RecordInfo(typeof(T));

            //recuperar os fields
            FieldInfo[] fields = typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

            //recuperar os atributos dos fields e os tamanhos
            _recordSize = 0;
            for (int i = 0; i < fields.Length; i++)
            {
                object[] fAttributes = fields[i].GetCustomAttributes(typeof(FieldFixedLengthAttribute), true);

                if (fAttributes != null && fAttributes.Length == 1)
                    _recordSize += ((FieldFixedLengthAttribute)fAttributes[0]).Length;
            }

        }
        public override object StringToField(string from)
        {
            string data = from;

            List<string> itens = new List<string>();
            while (!string.IsNullOrEmpty(data))
            {
                //cada registro possui 6 posicoes
                itens.Add(data.Substring(0, _recordSize));
                data = data.Remove(0, _recordSize);
            }

            List<T> records = new List<T>();
            foreach (string item in itens)
            {
                records.Add((T)_ri.StringToRecord(item));
            }

            return records;
        }

        public override string FieldToString(object from)
        {
            if (from is IList)
            {

                List<T> records = from as List<T>;
                StringBuilder sb = new StringBuilder();

                foreach (T record in records)
                {
                    sb.Append(_ri.RecordToString(record));
                }

                return sb.ToString();
            }
            else
                throw new ArgumentException("The argument must implement the IList interface");
        }
    }
}
